package com.nuoniu.sibanyun.service.finance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.VRuleVoucherType;
import com.nuoniu.sibanyun.mapper.finance.VRuleVoucherTypeMapper;
import com.nuoniu.sibanyun.service.finance.IVRuleVoucherTypeService;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 凭证分类 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2022-06-13
 */
@Service
public class VRuleVoucherTypeServiceImpl extends ServiceImpl<VRuleVoucherTypeMapper, VRuleVoucherType> implements IVRuleVoucherTypeService {

    @Override
    public List<VRuleVoucherType> getList(Integer type) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", UserThreadLocal.get().getCompanyId());
        if(type != null) {
            wrapper.eq("type", type);
        }
        return list(wrapper);
    }

    @Override
    public void saveType(VRuleVoucherType type) {
        Integer companyId = UserThreadLocal.get().getCompanyId();
        if(type.getId() == null) {
            type.setCompanyId(companyId);
        }

        VRuleVoucherType typeByName = baseMapper.getByName(type.getName(), companyId);
        if(typeByName != null && (type.getId() == null || !type.getId().equals(typeByName.getId()))) {
            throw new NuoNiuException("名称已存在");
        }
        this.saveOrUpdate(type);
    }

    @Override
    public void delete(Long id) {
        int count = baseMapper.getVoucherCount(id);
        if(count > 0) {
            throw new NuoNiuException("该分类已有凭证模版,不能删除");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", id);
        wrapper.eq("company_id", UserThreadLocal.get().getCompanyId());
        this.remove(wrapper);
    }
}
